
//
//  Ranting.swift
//  mm
//
//  Created by mac on 16/4/5.
//  Copyright © 2016年 Qingke. All rights reserved.
//

import UIKit

class Ranting: UIView {
    var ranting = 0 {
        didSet {
            if oldValue != ranting {
                print("你得了\(ranting)分")
                up()
            }
        }
    }
    var buttons = [UIButton]()
    let buttonHeight:CGFloat = 44
    let buttonWidth:CGFloat = 44
    let buttonSpace:CGFloat = 5
    let starNumber = 5
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        let emptyStar = UIImage(named: "emptyStar")
        let filledStar = UIImage(named: "filledStar")
        for i in 0 ..< starNumber {
            let button = UIButton()
            button.backgroundColor = UIColor.whiteColor()
            button .addTarget(self,action: "rantingTapped:",forControlEvents: .TouchDown)
            button.setImage(emptyStar, forState: .Normal)
            button.setImage(filledStar, forState: .Selected)
            button.setImage(filledStar, forState: [.Selected,.Highlighted])
            button.adjustsImageWhenHighlighted = false
            buttons += [button]
            addSubview(button)
            button.tag = i
            up()
        }
        
    }
    
    override func layoutSubviews() {
        var frame = CGRect(x: 0, y: 0, width: buttonWidth, height: buttonHeight)
        for button in buttons {
            button.frame = frame
            frame.origin.x += buttonWidth + buttonSpace
        }
    }
    func rantingTapped(button:UIButton) {
        
        ranting = button.tag + 1
        
       
    }
    func up() {
        for button in buttons {
            button.selected = button.tag < ranting
        }
    }
    override func intrinsicContentSize() -> CGSize {
        return CGSizeMake((buttonWidth + buttonSpace)*buttonSpace, buttonHeight)
    }


}
